package com.jh.user.service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.jh.user.business.BrandManageBusiness;
import com.jh.user.business.ChannelRateBusiness;
import com.jh.user.business.ThirdLeveDistributionBusiness;
import com.jh.user.business.UserBalanceBusiness;
import com.jh.user.business.UserBankInfoBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.business.UserRoleResourceBusiness;
import com.jh.user.business.UserShopsBusiness;
import com.jh.user.pojo.Brand;
import com.jh.user.pojo.BrandRate;
import com.jh.user.pojo.ChannelRate;
import com.jh.user.pojo.User;
import com.jh.user.pojo.UserAccount;
import com.jh.user.pojo.UserRole;
import com.jh.user.pojo.UserRoleForm;
import com.jh.user.util.Util;

import cn.jh.common.tools.ResultWrap;
import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import cn.jh.common.utils.ExceptionUtil;
import cn.jh.common.utils.TokenUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



@Controller
@EnableAutoConfiguration
public class UserService {

	private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
	
	@Autowired 
	private UserBalanceBusiness userBalBusiness;
		
	@Autowired 
	private BrandManageBusiness brandMangeBusiness;
	
	@Autowired
	private UserLoginRegisterBusiness  userLoginRegisterBusiness;
	
	@Autowired 
	private UserShopsBusiness userShopsBusiness;
	
	@Autowired
	private UserBankInfoBusiness userBankInfoBusiness;
	
	@Autowired
	private ThirdLeveDistributionBusiness  thirdLevelBusiness;
	
	@Autowired
	private UserRoleResourceBusiness userRoleResourceBusiness;
	
	@Autowired
	private ChannelRateBusiness channelRateBusiness;
	
	@Autowired 
	private ChannelService channelService;
	
	@Value("${user.background.uploadpath}")
	private String uploadImg;
	
	@Value("${user.background.downloadpath}")
	private String downloadImg;
	
	@Value("${spring.cloud.client.ipAddress}")
	private String serverIpAddress;
	
	@Autowired
	Util util;
	
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/find/newuser/num")
	public @ResponseBody Object findUsergetnewnum(HttpServletRequest request,
			@RequestParam(value = "brand_id" , defaultValue = "-1", required = false) long brandId,
			 //开始时间
			 @RequestParam(value = "start_time",  required = false) String  startTime,
			 //结束时间
			 @RequestParam(value = "end_time",  required = false) String endTime
			){
		Date StartTimeDate = null;
		if(startTime != null  && !startTime.equalsIgnoreCase("")){
			StartTimeDate = DateUtil.getDateFromStr(startTime);
		}
		Date endTimeDate = null; 
		if(endTime != null  && !endTime.equalsIgnoreCase("")){
			endTimeDate = DateUtil.getDateFromStr(endTime);
		}
		
		Map map = new HashMap();
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESULT, userLoginRegisterBusiness.queryUserNumByBidandtime(brandId,StartTimeDate,endTimeDate));
		map.put(CommonConstants .RESP_MESSAGE, "查询成功");
		return map;
	}
	
	//获取shops表中随机的userid
	@ResponseBody
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/query/randomuserid")
	public Object queryRandomUserid(HttpServletRequest request) {
		Random rand = new Random();
		Map map = new HashMap();
		try {
			String[] listuserid = userShopsBusiness.queryRandomUseridByAll();
			String userid = listuserid[rand.nextInt(listuserid.length-1)];
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESULT, userid);
			map.put(CommonConstants .RESP_MESSAGE, "获取成功");
		} catch (Exception e) {
			LOG.error(e.getMessage());
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "数据为空");
		}
		return map;
	}
	
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/query/by/phone/and/brandid")
	public @ResponseBody Object findUserByPhoneAndBrandId(HttpServletRequest request,
			@RequestParam(value="phone")String phone,
			@RequestParam(value="brandId")String brandId
			){
		Map<String,Object> map = new HashMap<String,Object>();
		User model = null;
		try {
			model = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, Long.valueOf(brandId));
		} catch (Exception e) {
			LOG.error("根据phone和brandId查询用户异常,参数为phone="+phone+",brandId="+brandId+";");
			e.printStackTrace();LOG.error(ExceptionUtil.errInfo(e));
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "查询用户失败,请检查输入的参数是否正确");
			return map;
		}
		if(model==null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "无该用户,请确认该用户已注册!");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功!");
		map.put(CommonConstants.RESULT, model);
		return map;
		
	}
	
	// 用户注销接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/delete/deleteUser")
	@ResponseBody
	public Object offUserActive(HttpServletRequest request, 
			@RequestParam(value = "phone",defaultValue="", required=false) String phone,
			@RequestParam(value = "brandId",defaultValue="-1", required=false) long brandid,
			@RequestParam(value = "id",defaultValue="-1", required=false) long userid) {
		Map map = new HashMap();
		
		if (("".equals(phone) || phone == null) && brandid == -1 && userid == -1) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "必须输入至少一种查询条件");
			return map;
		}else if (userid == -1) {
			List<User> user = userLoginRegisterBusiness.queryUsersByPhone(phone);
			if (user.size() == 0) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "该用户不存在");
				return map;
			} else {
				userid = user.get(0).getId();
			}
		}else if ((phone == null || "".equals(phone)) && brandid == -1) {
			LOG.info("============我是输入的userid============"+userid);
		}

		List<User> userLower = userLoginRegisterBusiness.findAfterUsers(userid);

		Brand brand = brandMangeBusiness.findBrandByManageid(userid);

		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/queryorderfailed";
		String result = "";
		try {
			requestEntity.add("userid", userid + "");
			result = restTemplate.postForObject(url, requestEntity, String.class);
			LOG.info("RESULT================" + result);
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONArray resultArr = jsonObject.getJSONArray("result");

		UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(userid);
		double userBalance = 0.00;
		if (userAccount == null) {
			userBalance = 0.00;
		} else {
			userBalance = userAccount.getBalance().doubleValue();
			if (userBalance == 0.0) {
				userBalance = 0.00;
			} else {
				userBalance += 9;
			}
		}

		if (userLower.size() == 0 && brand == null && resultArr.size() == 0 && userBalance == 0.00) {

			uri = util.getServiceUrl("paymentchannel", "error url request!");
			url = uri.toString() + "/v1.0/paymentchannel/realname/delrealname";
			try {
				requestEntity = new LinkedMultiValueMap<String, String>();
				requestEntity.add("userId", userid + "");
				result = restTemplate.postForObject(url, requestEntity, String.class);
				LOG.info("RESULT================" + result);
			} catch (Exception e) {
				LOG.error(e.getMessage());
			}
			try {
				userLoginRegisterBusiness.delUserByUserid(userid);
			} catch (Exception e) {
				LOG.info(e.getMessage());
				LOG.info("result========================还没有删除user表中记录");
			}
			userLoginRegisterBusiness.delUserByUserId(userid);

			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "注销成功");
		} else {
			if (userLower.size() != 0) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "该用户存在下级会员");
			}else if (brand != null) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "brand表中存在该用户");
			}else if (resultArr.size() != 0) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "该用户有待完成或已成功订单");
			}else if (userBalance != 0.00) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "该用户余额不为0");
			}
		}
		return map;
	}
	
	//代理商授权功能接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/auto/oriphone/{token}")
	@ResponseBody
	public Object userAuthManage(HttpServletRequest request,
			@PathVariable("token") String token,
			//被授权者手机号
			@RequestParam(value = "phone") String oriphone,
			//参数权限
			@RequestParam(value = "roleId") long roleid,
			
			@RequestParam(value = "lower_level", defaultValue = "0", required = false) int lowerLevel) {
		
		Map map = new HashMap();
		
		long userId;
		try {
			userId = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		
		List<User> userOri = userLoginRegisterBusiness.queryUsersByPhone(oriphone);
		int userOriSize = userOri.size();
		if (userOriSize == 0) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该用户不存在,请仔细核对用户手机号。");
			return map;
		}
		long userOriId = 0;
		long userOriBrandid = 0;
		for (int i = 0; i < userOriSize; i++) {
			userOriId = userOri.get(0).getId();
			userOriBrandid = userOri.get(0).getBrandId();
		}
		
		Long[] str2 = getUseridArray(userId,lowerLevel);
		
		if (userOri !=null && ArrayUtils.contains(str2, userOriId)) {
			UserRole userroleAuto = userRoleResourceBusiness.UserRolepageByRUid(userId);
			UserRole userroleOri = userRoleResourceBusiness.UserRolepageByRUid(userOriId);
			long roleIdAuto = userroleAuto.getRoleId();
			long roleIdOri = 0;
			if (userroleOri == null) {
				roleIdOri = -1;
			}else {
				roleIdOri = userroleOri.getRoleId();
			}
			
			long[] roleName = {5,4,3,2,1};
			int indexAuto = 0;
			int indexOri = 0;
			int indexRoleid = 0;
			for (int i = 0; i < roleName.length; i++) {
				if (roleIdAuto == roleName[i]) {
					indexAuto = i;
				}
				if (roleid == roleName[i]) {
					indexRoleid = i;
				}
				if (roleIdOri != -1 && roleIdOri == roleName[i]) {
					indexOri = i;
				}else if (roleIdOri == -1) {
					indexOri = -1;
				}
			}
			if (indexAuto <= indexOri) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "该用户权限大于等于您的权限");
				return map;
			}
			try {
				if (userroleOri != null && indexOri < indexAuto && indexRoleid < indexAuto) {
					userRoleResourceBusiness.upuserRole(userOriId, roleid);
				}else if(indexOri < indexAuto && indexRoleid < indexAuto) {
					UserRole role = new UserRole();
					role.setCreateTime(new Date());
					role.setCertigierUserId(userId);
					role.setBrandId(userOriBrandid);
					role.setRoleId(roleid);
					role.setUserId(userOriId);
					role.setStatus("0");
					userRoleResourceBusiness.adduserRole(role);
				}else {
					LOG.info("=============您设置的权限大于等于您的权限===========");
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "该用户不存在且您设置的权限大于等于您的权限");
					return map;
				}
			} catch (Exception e) {
				LOG.info(e.getMessage());
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "设置时权限出现异常");
				return map;
			}
		}else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该用户不是您的直推或间推");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}
	
	// 代理商费率设置接口
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/update/channelrate/{token}")
	@ResponseBody
	public Object userUpdateChannelRate(HttpServletRequest request, 
			@PathVariable("token") String token,
			@RequestParam(value = "phone") String phone,
			@RequestParam(value = "rate") BigDecimal rate,
			@RequestParam(value = "channelId") long channelid,
			@RequestParam(value = "lower_level", defaultValue = "0", required = false) int lowerLevel) {
		Map map = new HashMap();
		
		long userid;
		long userAutoBrandid;
		try {
			userid = TokenUtil.getUserId(token);
			userAutoBrandid = TokenUtil.getBrandid(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}

		User userOri = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, userAutoBrandid);
		if (userOri == null) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该用户不存在,请仔细核对用户手机号。");
			return map;
		}
		long userOriId = userOri.getId();
		
		Long[] str2 = getUseridArray(userid,lowerLevel);
		if (str2.length == 0) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该用户没有直推或间推");
			return map;
		}
		
		if (userOri !=null && ArrayUtils.contains(str2, userOriId)) {
			ChannelRate channelRateOri = channelRateBusiness.findChannelRateByUserid(userOriId, channelid);
			BrandRate userAuto = brandMangeBusiness.findRateByBrandAndChannel(userAutoBrandid, channelid);
			BigDecimal extraFee = userAuto.getExtraFee();
			BigDecimal withdrawFee = userAuto.getWithdrawFee();
			BigDecimal channelRate = userAuto.getRate();
			ChannelRate channelRateAuto = channelRateBusiness.findChannelRateByUserid(userid, channelid);
			BigDecimal channelrateAuto;
			if (channelRateAuto == null) {
				channelrateAuto = userAuto.getRate();
			} else {
				channelrateAuto = channelRateAuto.getRate();
			}
			if (channelRateOri == null) {
				ChannelRate oriChannelRate = new ChannelRate();
				oriChannelRate.setBrandId(userAutoBrandid);
				oriChannelRate.setChannelId(channelid);
				oriChannelRate.setRate(channelRate);
				oriChannelRate.setExtraFee(extraFee);
				oriChannelRate.setUserId(userOriId);
				oriChannelRate.setWithdrawFee(withdrawFee);
				channelRateBusiness.mergeChannelRate(oriChannelRate);
				LOG.info("=========channelrate表中没有该用户，已重新添加成功=========");
			}
			try {
				int result = channelrateAuto.compareTo(rate);
				if (result != 1) {
					channelRateBusiness.updChannelRateBybrandidAndChannelidanduserId(rate, userAutoBrandid, channelid, userOriId);
					LOG.info("=========channelrate表中该用户费率已经修改成功=========");
				} else {
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE, "该用户费率低于您的费率");
					return map;
				}
			} catch (Exception e) {
				LOG.info(e.getMessage());
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "用户通道费率查询返回为null");
				return map;
			}
		}else {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "该用户不是您的直推或间推");
			return map;
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "成功");
		return map;
	}
	
	private Long[] getUseridArray(long userId, int lowerLevel) {
		List<User> users = new ArrayList<User>();
		List<User> iusers = new ArrayList<User>();
		Long[] str2 = { userId };
		for (int i = 1; lowerLevel == 0 ? (i > 0) : (i <= lowerLevel); i++) {
			StringBuilder sbd = new StringBuilder();
			iusers = userLoginRegisterBusiness.findInfoUsers(str2);
			if (iusers.size() == 0) {
				int userlength = users.size();
				str2 = new Long[userlength];
				for (int j = 0; j < userlength; j++) {
					long userj = users.get(j).getId();
					str2[j] = userj;
				}
				break;
			}
			for (User iuser : iusers) {
				users.add(iuser);
				sbd.append(iuser.getId() + ",");
			}
			if (sbd.length() > 0) {
				String[] str1 = sbd.toString().split(",");
				str2 = new Long[str1.length];
				int str1length = str1.length;
				for (int j = 0; j < str1length; j++) {
					str2[j] = Long.valueOf(str1[j]);
				}
			}
		}
		return str2;
	}
	
	//查询代理商权限下所有下级会员的信息
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userrole/querybyroleid/{token}")
	@ResponseBody
	public Object queryOriRoleidByRoleid(HttpServletRequest request,
			@PathVariable("token") String token,
			@RequestParam(value = "page", defaultValue = "0", required = false) int page,
			@RequestParam(value = "size", defaultValue = "20", required = false) int size,
			@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
			@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty){
		Map map = new HashMap();
		Pageable pageable = new PageRequest(page, size, new Sort(direction,sortProperty));
		long userid;
		try {
			userid = TokenUtil.getUserId(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		
		Page<UserRole> userrole = userRoleResourceBusiness.findUserRoleByRoleid(userid, pageable);
		long userroleSize = userrole.getTotalElements();
		if (userroleSize == 0) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "没有下级会员被授权此权限！");
			return map;
		}
		List<Map> userInfo = new ArrayList<Map>();
		for (UserRole forUserRole : userrole) {
			Map map1 = new HashMap();
			long userId = forUserRole.getUserId();
			User user = userLoginRegisterBusiness.queryUserById(userId);
			if (user == null) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, "该下级会员已经不存在了！");
				return map;
			}
			int shopstatus = Integer.parseInt(user.getShopsStatus());
			map1.put("userid", userId);
			map1.put("phone", user.getPhone());
			map1.put("fullname", user.getFullname());
			map1.put("roleid", user.getGrade());
			map1.put("status", forUserRole.getStatus());
			map1.put("usershopStatus", shopstatus==1?"1":(shopstatus==0)?"0":(shopstatus==2)?"2":"3");
			map1.put("realnameStatus", user.getFullname()==null?"2":"1");
			map1.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(forUserRole.getCreateTime()));
			userInfo.add(map1);
		}
		
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, userInfo);
		return map;
	}
	
	// 查询该用户权限下会员的信息
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userrole/querybyuserid/{token}")
	@ResponseBody
	public Object queryOriRoleidByUserid(HttpServletRequest request,
			@PathVariable("token") String token) {
		Map map = new HashMap();
		long userid;
		long brandid;
		try {
			userid = TokenUtil.getUserId(token);
			brandid = TokenUtil.getBrandid(token);
		} catch (Exception e) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
			map.put(CommonConstants.RESP_MESSAGE, "token无效");
			return map;
		}
		Brand brand = brandMangeBusiness.findBrandById(brandid);
		List<UserRole> userrole = null;
		if (brand.getManageid() == userid) {
			userrole = userRoleResourceBusiness.findUserRoleByBrandid(brandid);
		} else {
			userrole = userRoleResourceBusiness.findUserRoleByUserid(userid);
		}
		if (userrole.size() == 0) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您没有下级会员");
		}else {
			int userroleSize = userrole.size();
			List<Map> listMap = new ArrayList<Map>();
			for (int i = 0; i < userroleSize; i++) {
				Map userMap = new HashMap();
				long oriUserid = userrole.get(i).getUserId();
				User oriUser = userLoginRegisterBusiness.queryUserById(oriUserid);
				userMap.put("userinfo", oriUser);
				listMap.add(userMap);
			}
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "查询成功");
			map.put(CommonConstants.RESULT, listMap);
		}
		return map;
	}

	//临时使用，添加t_user_role两个字段信息
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/userrole/querybyuserid/linshi")
	@ResponseBody
	public Object queryOriRoleidByLinshi(HttpServletRequest request) {
		Map map = new HashMap();
		List userrole = userRoleResourceBusiness.queryFindAll();
		Long[] usersid = new Long[userrole.size()];
		for (int i = 0; i < usersid.length; i++) {
			usersid[i] = (Long) userrole.get(i);
			User user = userLoginRegisterBusiness.queryUserById(usersid[i]);
			long brandid = 0;
			if (user != null) {
				brandid = user.getBrandId();
			}
			Brand branduser = userLoginRegisterBusiness.findBrandByBrandid(brandid);
			long brandManage = 0;
			if (branduser != null) {
				brandManage = branduser.getManageid();
			}
			userLoginRegisterBusiness.updateByAll(brandManage, usersid[i], brandid);
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "修改成功");
		return map;
	}
	
	
	//直推排行
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/")
	@ResponseBody
	public Object queryOriRoleidByRoleid(HttpServletRequest request,
			@RequestParam(value = "brand_id"   ) long brandid,
			@RequestParam(value = "endtime" , required=false  ) String endtime,
			@RequestParam(value = "starttime" , required=false  ) String startTime,
			@RequestParam(value = "size" , required=false , defaultValue="10" ) int size) {
		
		
		List<UserRoleForm> ufList= userLoginRegisterBusiness.findUserPreList(brandid, startTime, endtime, size);
		Map map =new HashMap();
		
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "修改成功");
		map.put(CommonConstants.RESULT, ufList);
		return map;
	}
		
		//后台上传分享二维码背景图
		@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/background/uploads")
		public @ResponseBody Object uploadBackgroundImgs(HttpServletRequest request,
				@RequestParam(value="brandId") long brandid,
				@RequestParam(value="phone") String phone,
				@RequestParam(value="files") MultipartFile[] files){
				Map map = new HashMap();
				User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
				if(user==null){
					map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE,"无此用户");
					return map;
				}else{	
					String path = "appsm";
					File dir = new File(uploadImg + brandid + "/"+path);
					// 创建目录
					if (dir.mkdirs()) {
						System.out.println("创建目录" + uploadImg + brandid + "/"+path+":成功！");

					} else {
						File[] tempfiles = dir.listFiles();
						for (File file : tempfiles) {
						}

						System.out.println("创建目录" + uploadImg + brandid + "/"+path+":失败！");
					}

					if (files != null && files.length > 0) {
						for (int i=0;i<files.length;i++) {
							 String fileName=files[i].getOriginalFilename();//获取文件名加后缀
							 String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
				                fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
							File dest = new File(uploadImg + brandid + "/"+path+"/"+fileName);
							try {
								files[i].transferTo(dest);
							} catch (IllegalStateException e) {
								LOG.info(e.getMessage());
							} catch (IOException e) {
								LOG.info(e.getMessage());
							}
						}
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE,"上传失败");
						return map;
					}
				}
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE,"上传成功");
				return map;
		}
		
		//app获取二维码分享图片
		@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/background/downloads")
		public @ResponseBody Object downloadPic(HttpServletRequest request,
				@RequestParam(value="brandid") String brandId,
				@RequestParam(value="phone") String phone){
			
			Map map = new HashMap();
			long brandid = Long.parseLong(brandId);
		
			User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
			if(user==null){
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE,"无此用户信息");
				return map;
			}
			List<String> filepaths  = new ArrayList<String>();
			String path = "appsm";
			if( brandId!=null && !brandId.equals("")){
				File file = new File(uploadImg + brandid+"/"+path); 
				String[] filelist = file.list();
				if(filelist!=null){
					for(int i = 0; i < filelist.length; i++) {
			           filepaths.add(downloadImg + brandid+"/"+path + "/" + filelist[i]);
			        }
				}
			}else{
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE,"无二维码分享背景图");
				return map;
			}
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE,"获取成功");
			map.put(CommonConstants.RESULT,filepaths);
			return map;
		}
		
		//后台上传二维码
		@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/demoCode/uploads")
		public @ResponseBody Object uploadDemoCode(HttpServletRequest request,
				@RequestParam(value="brandId") long brandid,
				@RequestParam(value="phone") String phone,
				@RequestParam(value="files") MultipartFile[] files){
				Map map = new HashMap();
				User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
				if(user==null){
					map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
					map.put(CommonConstants.RESP_MESSAGE,"无此用户");
					return map;
				}else{	
					String path = "demoCode";
					File dir = new File(uploadImg + brandid + "/"+path);
					// 创建目录
					if (dir.mkdirs()) {
						System.out.println("创建目录" + uploadImg + brandid + "/"+path+":成功！");

					} else {
						File[] tempfiles = dir.listFiles();
						for (File file : tempfiles) {
						}

						System.out.println("创建目录" + uploadImg + brandid + "/"+path+":失败！");
					}

					if (files != null && files.length > 0) {
						for (int i=0;i<files.length;i++) {
							 String fileName=files[i].getOriginalFilename();//获取文件名加后缀
							 String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
				                fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;//新的文件名
							File dest = new File(uploadImg + brandid + "/"+path+"/"+fileName);
							try {
								files[i].transferTo(dest);
							} catch (IllegalStateException e) {
								LOG.info(e.getMessage());
							} catch (IOException e) {
								LOG.info(e.getMessage());
							}
						}
					}else{
						map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
						map.put(CommonConstants.RESP_MESSAGE,"上传二维码失败");
						return map;
					}
				}
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE,"上传成功");
				return map;
		}
		
		
		//app获取二维码图片
		@RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/demoCode/downloads")
		public @ResponseBody Object downloadDemoCode(HttpServletRequest request,
				@RequestParam(value="brandid") String brandId,
				@RequestParam(value="phone") String phone){
			
			Map map = new HashMap();
			long brandid = Long.parseLong(brandId);
		
			User user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
			if(user==null){
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE,"无此用户信息");
				return map;
			}
			List<String> filepaths  = new ArrayList<String>();
			String path = "demoCode";
			if( brandId!=null && !brandId.equals("")){
				File file = new File(uploadImg + brandid+"/"+path); 
				String[] filelist = file.list();
				if(filelist!=null){
					for(int i = 0; i < filelist.length; i++) {
			           filepaths.add(downloadImg + brandid+"/"+path + "/" + filelist[i]);
			        }
				}
			}else{
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE,"无二维码图片");
				return map;
			}
			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE,"获取成功");
			map.put(CommonConstants.RESULT,filepaths);
			return map;
		}
		
		@RequestMapping(method=RequestMethod.POST,value="/v1.0/user/get/usercount/by/phone")
		public @ResponseBody Object getUserGrade(
				@RequestParam(value="phone")String phone,
				@RequestParam(value="brandId")String brandId
				){
			List<User> users = userLoginRegisterBusiness.findByBrandIdAndPhoneLike(Long.valueOf(brandId),phone+"%");
			if (users == null || users.size() < 2) {
				return ResultWrap.init(CommonConstants.FALIED, "无其他等级用户");
			}else{
				return ResultWrap.init(CommonConstants.SUCCESS, "有其他等级用户");
			}
		}
		
}



